package com.boang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boang.domain.Admin;
import com.boang.domain.Role;
import com.boang.service.AdminService;
import com.boang.mapper.AdminMapper;
import com.boang.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author 13813
 * @description 针对表【admin】的数据库操作Service实现
 * @createDate 2024-08-09 15:39:29
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements AdminService, UserDetailsService {

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //select * from admin where name = 'admin'
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getName, username);

        //根据用户名查询用户信息
        Admin admin = this.baseMapper.selectOne(lambdaQueryWrapper);

        if (Objects.isNull(admin)) {
            throw new UsernameNotFoundException("无此用户");
        }

        //获取用户的角色
        List<Role> roleList = roleService.getRoleListByAdminName(admin.getName());
        List<SimpleGrantedAuthority> authorityList = roleList.stream().map(role -> {
            return new SimpleGrantedAuthority("ROLE_" + role.getRoleCode());
        }).toList();

        //权限
//        List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin,ROLE_dev,ROLE_test,prod,pre");
        return new User(admin.getName(), admin.getPassword(), authorityList);
    }
}




